package com.krause.marinechart.iso8211;

import java.util.ArrayList;

import com.krause.marinechart.iso8211.Directory.FieldDef;


public class Data implements Constants {
	
	ArrayList<Field> fields;
	
	public Data (byte[] mDataArray, Directory mDirectory) {
		fields = new ArrayList<Field>(); 
		for(FieldDef fieldDef : mDirectory.fieldDefs) {
			fields.add(new Field(mDataArray, fieldDef.fieldPos, fieldDef.fieldLength));
			Module.sb.append(new Field(mDataArray, fieldDef.fieldPos, fieldDef.fieldLength));
		}
	}
	
	protected class Field {
		ArrayList<SubField> subFields;
		
		protected Field (byte[] mDataArray, int startByte, int fieldLength) {
			subFields = new ArrayList<SubField>();
			for(int i = startByte; i < (startByte + fieldLength); i++) {
				int subStartByte = i;
				while (mDataArray[i] != DDF_FIELD_TERMINATOR && mDataArray[i] != DDF_UNIT_TERMINATOR) {
					i++;
				}
				subFields.add(new SubField(mDataArray, subStartByte, i));
			}
		}
		
		@Override
		public String toString() {
			StringBuffer sb = new StringBuffer();
			for(SubField subField : subFields) {
				sb.append(subField + "\n");
			}
			return new String(sb);
		}
		
		protected class SubField {
			protected byte[] subField;
			
			protected SubField (byte[] mDataArray, int startByte, int endByte) {
				subField = new byte[endByte - startByte];
				System.arraycopy(mDataArray, startByte, subField, 0, subField.length);
			}
			
			@Override
			public String toString() {
				return new String(subField);
			}
			
		}
	}

}
